package flc.ast.utils;

import android.content.Context;

import androidx.exifinterface.media.ExifInterface;

import android.content.ContentResolver;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class ImageLocationUtils {
    /**
     * 从图片中获取拍摄城市
     * 注意：此方法需要在后台线程调用，避免阻塞主线程
     *
     * @param context   上下文
     * @param imagePath 图片路径
     * @return 城市名称，若无法获取则返回null
     */
    public static String getCityFromImage(Context context, String imagePath) {
        Log.d("ImageLocationUtils", "尝试获取图片城市信息，路径: " + imagePath);
        if (context == null) {
            Log.e("ImageLocationUtils", "上下文为空");
            return null;
        }
        if (imagePath == null || imagePath.isEmpty()) {
            Log.e("ImageLocationUtils", "图片路径为空或无效");
            return null;
        }

        ExifInterface exif = null;
        try {
            // 支持Content URI和文件路径两种格式
            if (imagePath.startsWith(ContentResolver.SCHEME_CONTENT)) {
                Log.d("ImageLocationUtils", "使用Content URI读取图片: " + imagePath);
                Uri uri = Uri.parse(imagePath);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    exif = new ExifInterface(context.getContentResolver().openInputStream(uri));
                } else {
                    Log.e("ImageLocationUtils", "Android N以下版本不支持Content URI直接读取Exif");
                    return null;
                }
            } else {
                // 检查文件是否存在
                File imageFile = new File(imagePath);
                if (!imageFile.exists()) {
                    Log.e("ImageLocationUtils", "图片文件不存在: " + imagePath);
                    return null;
                }
                if (!imageFile.canRead()) {
                    Log.e("ImageLocationUtils", "没有读取图片文件的权限: " + imagePath);
                    return null;
                }
                exif = new ExifInterface(imagePath);
            }

            if (exif == null) {
                Log.e("ImageLocationUtils", "无法创建ExifInterface实例");
                return null;
            }

            // 检查是否有GPS信息
            String gpsLatitude = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
            String gpsLongitude = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
            String gpsLatitudeRef = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
            String gpsLongitudeRef = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
            Log.d("ImageLocationUtils", "GPS信息存在: 纬度=" + gpsLatitude + ", 经度=" + gpsLongitude + ", 纬度参考=" + gpsLatitudeRef + ", 经度参考=" + gpsLongitudeRef);

            float[] latLong = new float[2];
            boolean hasLatLong = exif.getLatLong(latLong);
            Log.d("ImageLocationUtils", "Exif获取经纬度结果: " + hasLatLong + ", 纬度=" + latLong[0] + ", 经度=" + latLong[1]);

            // 如果getLatLong失败，尝试手动解析GPS信息
            if (!hasLatLong && gpsLatitude != null && gpsLongitude != null && gpsLatitudeRef != null && gpsLongitudeRef != null) {
                Log.d("ImageLocationUtils", "尝试手动解析GPS经纬度");
                double latitude = convertGpsToDecimal(gpsLatitude, gpsLatitudeRef);
                double longitude = convertGpsToDecimal(gpsLongitude, gpsLongitudeRef);
                latLong[0] = (float) latitude;
                latLong[1] = (float) longitude;
                hasLatLong = true;
                Log.d("ImageLocationUtils", "手动解析结果: 纬度=" + latitude + ", 经度=" + longitude);
            }

            if (!hasLatLong) {
                Log.e("ImageLocationUtils", "图片中不包含位置信息");
                return null;
            }

            double latitude = latLong[0];
            double longitude = latLong[1];

            // 检查Geocoder是否可用
            if (!Geocoder.isPresent()) {
                return null;
            }

            // 反向地理编码
            Geocoder geocoder = new Geocoder(context, Locale.CHINA);
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            Log.e("ImageLocationUtils", "城市："+addresses);
            if (addresses != null && !addresses.isEmpty()) {
                Address address = addresses.get(0);
                // 获取城市，优先获取locality，若为空则获取adminArea
                String city = address.getLocality();
                if (city == null) {
                    city = address.getAdminArea();
                }
                return city;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            // 可能没有读取文件的权限
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将GPS经纬度从度分秒格式转换为十进制
     */
    private static double convertGpsToDecimal(String gpsValue, String ref) {
        try {
            String[] parts = gpsValue.split(",");
            String[] degrees = parts[0].split("/");
            double degreesDouble = Double.parseDouble(degrees[0]) / Double.parseDouble(degrees[1]);

            String[] minutes = parts[1].split("/");
            double minutesDouble = Double.parseDouble(minutes[0]) / Double.parseDouble(minutes[1]);

            String[] seconds = parts[2].split("/");
            double secondsDouble = Double.parseDouble(seconds[0]) / Double.parseDouble(seconds[1]);

            double result = degreesDouble + (minutesDouble / 60) + (secondsDouble / 3600);
            if (ref.equals("S") || ref.equals("W")) {
                result = -result;
            }
            return result;
        } catch (Exception e) {
            Log.e("ImageLocationUtils", "GPS坐标转换失败: " + e.getMessage());
            return 0;
        }
    }
}
